package com.inspinia.base.util;

import com.inspinia.base.util.properties.HttpConfig;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * http辅助类
 *
 * @author fengwx
 */
public class HttpUtils {
    //验证sessionId
    public static String[] sessionId;
    //编码格式
    public static final String ENCODE = "UTF-8";
    private static Logger log = LoggerFactory.getLogger(HttpUtils.class);
    //http的ip地址和端口号
    public static String httpIp = HttpConfig.httpIp;

    /**
     * get方法
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String get(String url) throws Exception {
        log.info("[HTTP][GET]" + url);
        CloseableHttpClient httpClient = HttpClientPool.getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            log.info("[HTTP-GET]请求失败，HTTP STATUS CODE ＝ {}", statusCode);
            throw new HttpException(statusCode, "HTTP请求失败");
        }
        String result = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);

        log.info("[HTTP][GET][RESULT]" + result);
        return result;
    }

    /**
     * post请求
     *
     * @param url  方法url
     * @param data 参数
     * @return
     * @throws Exception
     */
    public static void post(String url, Map<String, String> data) throws IOException {
        if (!url.startsWith("/")) {
            url = httpIp + "/" + url;
        } else {
            url = httpIp + url;
        }
        CloseableHttpClient httpclient = HttpClientPool.getHttpClient();
        HttpPost httppost = new HttpPost(url);
//        httppost.addHeader("sign", SystemConfig.API_SIGN_CLIENT);
        String filePath = data.get("filePath");
        FileBody bin = null;
       // MultipartEntityBuilder reqEntity = new MultipartEntityBuilder(HttpMultipartMode.BROWSER_COMPATIBLE, "---------", Charset.forName("UTF-8"));
        MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create().setBoundary("---------").setCharset(Charset.forName("UTF-8")).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (filePath != null) {
            bin = new FileBody(new File(filePath));
            reqEntity.addPart("file", bin);
        }
        StringBody comment = new StringBody(URLEncoder.encode(data.get("requestJson"), "UTF-8"));
        reqEntity.addPart("requestJson", comment);
        httppost.setEntity(reqEntity.build());
        HttpResponse response = httpclient.execute(httppost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode >= 400) {
            log.info("[HTTP-POST]请求失败，HTTP STATUS CODE ＝ {}", statusCode);
            throw new HttpException(statusCode, "HTTP请求失败");

        }else {
            HttpEntity resEntity = response.getEntity();
            EntityUtils.consume(resEntity);
        }
        HttpClientPool.consume(httppost.getEntity());
    }

    /**
     * 登陆验证,获取sessionId
     *
     * @throws IOException
     */
    public static void login(String url, String username, String password) throws IOException {
        NameValuePair nameValuePair1 = new BasicNameValuePair("username", username);
        NameValuePair nameValuePair2 = new BasicNameValuePair("password", password);
        List nameValuePairs = new ArrayList();
        nameValuePairs.add(nameValuePair1);
        nameValuePairs.add(nameValuePair2);
        CloseableHttpClient httpClient = HttpClientPool.getHttpClient();
        HttpPost httpPost = new HttpPost(url); //设定请求方式
        if (nameValuePairs != null && nameValuePairs.size() != 0) {
            //把键值对进行编码操作并放入HttpEntity对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, Charset.forName(ENCODE)));
        }
        HttpResponse httpResponse = httpClient.execute(httpPost); // 发送请求并等待响应
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            httpPost.abort();
        }
        sessionId = httpResponse.getHeaders("Set-Cookie")[0].getValue().split(";");
    }

}

